package www.cskaoyan.com.controller;

import sun.misc.BASE64Decoder;
import www.cskaoyan.com.bean.ClassManager;
import www.cskaoyan.com.utils.Request;
import www.cskaoyan.com.utils.Response;

import java.io.*;
import java.sql.SQLException;

/**
 * @author snow
 * @ClassName ImgUploadController
 * @description: TODO:
 * @datetime 2023年 03月 17日 11:51
 */
public class ImgUploadController {

    private static String BASE_FILE_PATH = "C:\\gui-img\\";

    static {
        // 如果文件夹不存在, 创建该文件夹
        File file = new File(BASE_FILE_PATH);
        if (!file.exists()){
            file.mkdir();
        }
    }

    public Response fileUpload(Request request) throws IOException {
        System.out.println("/ImgUploadController/fileUpload");
        // System.out.println(request);
        // System.out.println(request.getParameters().get("imgBase64"));
        Response response = new Response(200, "图片上传完成", true);

        String filePath = BASE_FILE_PATH + request.getParameters().get("fileName");
        response.setData( request.getParameters().get("fileName"));


        BASE64Decoder base64Decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            out = new FileOutputStream(filePath);

            byte[] imgBase64s = base64Decoder.decodeBuffer((String) request.getParameters().get("imgBase64"));
            for (int i = 0; i < imgBase64s.length; i++) {
                if (imgBase64s[i] < 0){
                    imgBase64s[i] += 256;
                }
            }
            out.write(imgBase64s);
        } catch (FileNotFoundException e) {
            response = new Response(500, "图片上传发生异常", false);
            return response;
        } catch (IOException e) {
            response = new Response(500, "图片上传发生异常", false);
            return response;
        }finally {
            out.flush();
            out.close();
        }
        return  response;
    }
}
